// 工具集
import dayjs from 'dayjs'
import SparkMd5 from 'spark-md5'

// 写一个节流函数
export function throttle(fn, delay = 100) {
  let timer = null
  return function (...args) {
    if (!timer) {
      timer = setTimeout(() => {
        fn.apply(this, args)
        timer = null
      }, delay)
    }
  }
}

// 写一个防抖函数
export function debounce(fn, delay = 300) {
  let timer = null
  return function (...args) {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      fn.apply(this, args)
      timer = null
    }, delay)
  }
}

// 延时器
export const delay = (ms = 300) => {
  return new Promise(resolve => {
    setTimeout(resolve, ms)
  })
}

// 计算多当天到向后6天的日期写一个函数  dayjs momentjs
export const getRangeDay = (day = 6) => {
  let days = []
  let weeks = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
  for (let i = 1; i <= day; i++) {
    let week = ''
    let weekIndex = dayjs().add(i, 'day').format('d')
    if (i == 1) {
      week = '明天'
    } else if (i == 2) {
      week = '后天'
    } else {
      week = weeks[weekIndex]
    }
    let daytime = dayjs().add(i, 'day')
    let daystr = week + daytime.format('MM月DD日')
    days.push({ daytime: daytime.unix(), daystr })
  }
  return days
}

// 指定年份日期
export const getFullYearDay = (n = 20, type = 'year') => {
  let timestamp
  if (type === 'year') {
    timestamp = dayjs().add(n, 'year')
  } else {
    timestamp = dayjs().add(n, 'day')
  }

  return [timestamp.format('YYYY-MM-DD'), timestamp]
}
// 写一个判断是否是移动端
export const isMobile = () => {
  const userAgentInfo = navigator.userAgent
  const Agents = ['Android', 'iPhone', 'SymbianOS', 'Windows Phone', 'Mobile']
  return Agents.some(item => userAgentInfo.includes(item))
}


// 判断是否为空对象
export const isEmptyObj = obj => {
  return Object.keys(obj).length === 0 ? true : false
}
// 返回非空的对象属性
export const noEmptySearchObject=obj=>{
  let ret= {}
  for(let key in obj){
    if(obj[key]){
      ret[key]=obj[key]
    }
  }
  // 返回ret,为true判断不是对象，返回null，否则不变
  return isEmptyObj(ret) ? null :ret
}

// 把对象转成query字符串
export const objToQueryString = obj => {
  let ret = ''
  for (let key in obj) {
    ret += `&${key}=${obj[key]}`
  }
  return ret
}

// 把用户表中的记录的字段名称修改为中文名称
export const changeFieldToCh = key => {
  const columns = {
    username: '账号',
    realname: '姓名',
    sex: '性别',
    phone: '手机号',
    birthday: '生日'
  }
  return columns[key] ?? '未知'
}

//导出用户Excel数据处理
export const exportUserData=(
  userData,
  exclude = ['id', 'role', 'avatar', 'cname', 'password']
)=>{
return userData.map(item=>{
  let obj={}
  //遍历需要处理的数据
  for(let key in item) {
    //如果判断条件中不包含数据中的字段
    if(!exclude.includes(key)){
      //将符合条件的字段作为obj对象的属性，并赋值
      obj[changeFieldToCh(key)]=item[key]
    }
    // 对于sex字段进行特殊处理，值为1设置为属性时为'先生'，否则为'女士'
    if(key === 'sex')obj[changeFieldToCh(key)]=item[key]==='1' ? '先生' : '女士'
  }
  // 返回处理后的新数据
  return obj
})
}

// 读取本地File对象文件为ArrayBuffer
export const readAsArrayBuffer = file => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsArrayBuffer(file)
    reader.onload = e => {
      resolve(e.target.result)
    }
    reader.onerror = err => {
      reject(err)
    }
  })
}

// 根据文件内容生成hash值
export const fileContentToHash = async file => {
  let content = await readAsArrayBuffer(file)
  try {
    const sparkMd5 = new SparkMd5.ArrayBuffer()
    sparkMd5.append(content)
    return sparkMd5.end()
  } catch (error) {
    return ''
  }
}


